package com.xuhai.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuhai.blog.admin.entity.ExpiresEntity;
import com.xuhai.blog.admin.mapper.ExpiresMapper;
import com.xuhai.blog.admin.service.ExpiresService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhai.blog.common.shiro.TokenGenerator;
import com.xuhai.blog.common.util.ResultJson;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 登录有效期表 服务实现类
 * </p>
 *
 * @author 机蜂
 * @since 2022-02-08
 */
@Service
public class ExpiresServiceImpl extends ServiceImpl<ExpiresMapper, ExpiresEntity> implements ExpiresService {

    @Override
    public ResultJson saveToken(Integer userId) {
        /*生成token值*/
        String token= TokenGenerator.generateValue();
        /*设置有效期为12小时有效*/
        Date date=new Date();
        date.setHours(date.getHours()+12);
        /*根据用户ID获取token*/
        ExpiresEntity expiresEntity=getByUserId(userId);
        /*判断该用户是否存过token*/
        if(expiresEntity==null){
            /*新增用户登录*/
            expiresEntity=new ExpiresEntity();
            expiresEntity.setExpires(date);
            expiresEntity.setUserId(userId);
            expiresEntity.setToken(token);
            this.save(expiresEntity);
        }else{
            expiresEntity.setToken(token);
            expiresEntity.setExpires(date);
            this.updateById(expiresEntity);
        }
        return ResultJson.ok().data(token);
    }

    @Override
    public void logout(Integer userId) {
        ExpiresEntity expires=getByUserId(userId);
        if(expires!=null){
            expires.setToken(TokenGenerator.generateValue());
            this.updateById(expires);
        }
    }

    @Override
    public ExpiresEntity getByToken(String token) {
        return this.getOne(new QueryWrapper<ExpiresEntity>().eq("token",token));
    }

    private ExpiresEntity getByUserId(Integer userId){
        return this.getOne(new QueryWrapper<ExpiresEntity>().eq("user_id",userId));
    }
}
